package cn.hyh.core.service.impl;

import cn.hyh.core.component.CanTellUserException;
import cn.hyh.core.component.GlobalStatus;
import cn.hyh.core.costant.MsgStatus;
import cn.hyh.core.dao.BlogMapper;
import cn.hyh.core.dao.ContentMapper;
import cn.hyh.core.dao.DicsMapper;
import cn.hyh.core.dao.UserMapper;
import cn.hyh.core.pojo.*;
import cn.hyh.core.service.ServiceInterface.BlogService;
import cn.hyh.core.service.ServiceInterface.DicService;
import cn.hyh.core.util.DateUtils;
import cn.hyh.core.vo.BlogInfoModel;
import cn.hyh.core.vo.BlogPageDTO;
import cn.hyh.core.vo.PageModel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.datatype.jsr310.deser.InstantDeserializer;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ResourceUtils;

import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.*;

/**
 * @auther :hyh
 * @desc :
 * @date :2019/7/22
 */
@Service
public class BlogServiceImpl implements BlogService {

    @Value("${spring.servlet.multipart.location}")
    private String  imgsLoaction;

    @Value("${imgAccess.path}")
    private String imgAccessPath;

    @Value("${blog.default.img}")
    private  String  defaultImg;

    @Resource
    private ContentMapper contentMapper;

    @Resource
    private DicsMapper dicsMapper;

    @Resource
    private BlogMapper blogMapper;
    @Resource
    private UserMapper userMapper;

    @Autowired
    private DicService dicService;
    /**
     *  分页查询。。
     * @param pageModel
     * @return
     */
    @Override
    public Map<String, Object> selectPage(PageModel pageModel) {

        Map dicMap = dicService.selectGroup();
        List<Dics> list = (List<Dics>) dicMap.get("Label");
        Dics Label = null;
        for (Dics dic : list) {
            if (pageModel.getType().equals(dic.getValue())) {
                Label = dic;
            }
        }
        if (Label == null) {
            return  null;
        }
        int offset = (pageModel.getPageNum() - 1) * pageModel.getPageSize();
        Dics dics = dicsMapper.selectOne(new QueryWrapper<Dics>().eq("value", "全部").eq("group_name", "Label"));
        List<BlogPageDTO> page = contentMapper.selectByPage(offset, pageModel.getPageSize(), Label.getId(), dics.getId(), GlobalStatus.ORDER_DESC);
        System.out.println(page.size());

        int total = 0;
        if (Label.getId() == dics.getId()) {
            //说明是查询所有的。
            total = contentMapper.selectCount(null);
        }else{
              total=contentMapper.getTotalCountByFiled("tb_content", "label_id", Label.getId() + "");
        }

        Map<String, Object> map = new HashMap<>();
        map.put("pageList", page);
        map.put("totalCount", total);



        return map;
    }

    /**
     * 处理文件上传
     * @param file
     * @param request
     * @return
     */
    @Override
    public String HandleUploadImg(MultipartFile file, HttpServletRequest request) {
        if (file == null) {
            throw new CanTellUserException("请先上传图片!");
        }
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        if ("jpg".equals(extension.toLowerCase()) || "png".equals(extension.toLowerCase()) || "jpeg".equals(extension.toLowerCase())) {
            long size = file.getSize();
            if (size > 1024 * 1024 * 10) {
                throw new CanTellUserException("图片最大支持10M!");
            }
            try {
                URL url = ResourceUtils.getURL(imgsLoaction);
                System.out.println(url.getPath());
                String dateString = DateUtils.dateString(new Date());
                String dir = url.getPath() + dateString;
                File dest = new File(dir);
                if (!dest.exists()) {
                    dest.mkdirs();
                }
                File uploadFile = new File(dest, file.getOriginalFilename());
                file.transferTo(uploadFile);
                if(!System.getProperty("os.name").toLowerCase().startsWith("win")){
                    Runtime.getRuntime().exec("chmod  766" + uploadFile.getAbsolutePath());
                }
                String imgUrl = "http://"+request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                System.out.println("imgUrl==>" + imgUrl);
                int i = imgAccessPath.lastIndexOf("/");
                if (i != -1) {
                    imgAccessPath = imgAccessPath.substring(0, i+1);
                }
                imgUrl += imgAccessPath + dateString+"/" + file.getOriginalFilename();
                System.out.println("访问路径:" + imgUrl);
                return imgUrl;
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                throw new CanTellUserException("文件上传失败！");
            } catch (IOException e) {
                e.printStackTrace();
                throw new CanTellUserException("文件上传失败！");
            }

        } else {
            throw new CanTellUserException("只能上传jpg/png格式图片!");
        }
    }

    /**
     *  生成博客文章
     * @param model
     */
    @Transactional
    @Override
    public void writeBlog(BlogInfoModel model) {
        if (StringUtils.isEmpty(model.getContent())) {
            throw new CanTellUserException("博客内容不能为空!");
        }
        if (StringUtils.isEmpty(model.getTitle())) {
            throw new CanTellUserException("博客标题不能为空!");
        }
        if(null==dicsMapper.selectById(model.getLabel())){
            throw new CanTellUserException("分类标签不能为空!");
        }
        Subject subject = SecurityUtils.getSubject();
        if(!subject.isAuthenticated()){
            throw new CanTellUserException("请先登录!");
        }
        Content result = contentMapper.selectById(model.getContentId());
        if (result == null) {
            //新建文件
            Content content = new Content();
            content.setContent(model.getContent())
                    .setCreateTime(new Date())
                    .setLabelId(model.getLabel())
                    .setTitle(model.getTitle())
                    .setIndexImg(model.getImgUrl());
            if (StringUtils.isBlank(model.getDescription())) {
                content.setDescription("暂无描述!");
            }else {
                content.setDescription(model.getDescription());
            }
            if (StringUtils.isEmpty(model.getImgUrl())) {
                content.setIndexImg(defaultImg);
            }
            contentMapper.insert(content);

            Blog blog = new Blog();
            User currentUser = (User) subject.getPrincipal();
            blog.setAuthor(currentUser.getName())
                    .setCreateTime(new Date())
                    .setContentId(content.getId());
            blogMapper.insert(blog);
        }else {
             //旧文件， 修改对应的文件。
            result.setCreateTime(new Date())
                    .setIndexImg(model.getImgUrl())
                    .setTitle(model.getTitle())
                    .setLabelId(model.getLabel())
                    .setDescription(model.getDescription())
                    .setContent(model.getContent());
            contentMapper.updateById(result);
        }


    }

    /**
     *  异步动态查询。
     * @param queryString
     */
    @Override
    public List<Map<String,Object>> AsyncSerach(String queryString) {

      List<Content> list=  contentMapper.selectLikeSearch("%" + queryString + "%");
        List<Map<String,Object>> resultList = new ArrayList<>();
        if (list != null && list.size() > 0) {
              list.stream().forEach(con ->{
                  Map<String, Object> map = new HashMap<>();
                  map.put("value", con.getTitle());
                  map.put("id", con.getId());
                  resultList.add(map);
              });
        }
       return    resultList;

    }

    /**
     * 根据文章获取对应的文章详情。
     * @param id
     */
    @Override
    public BlogPageDTO getArticleDetail(int id) {
       BlogPageDTO   dto=   contentMapper.getBlog(id);
        if (dto == null) {
            throw new CanTellUserException("查询到对应的数据!请检查id");
        }
        //浏览量+1
        Blog blog = dto.getBlog();
        blog.setView(blog.getView() + 1);
        blogMapper.updateById(blog);
        return dto;
    }

    /**
     *  根据文章id 获取指定的信息
     * @param id
     * @return
     */
    @Override
    public List<Map<String, Object>> initCountData(int id) {
        if (id <= 0) {
            throw new CanTellUserException("输入id不合法");
        }
        List<Map<String, Object>> list = new ArrayList<>();
        int count = contentMapper.selectCount(null);
        Map<String, Object> countMap = new HashMap<>();
        countMap.put("date", "文章总数");
        countMap.put("name", count);
        list.add(countMap);

        Blog b = blogMapper.selectOne(new QueryWrapper<Blog>().eq("content_id", id));
        if (b == null) {
            throw  new CanTellUserException("查找不到对应的文章!");
        }
        Map<String, Object> commentCount = new HashMap<>();
        commentCount.put("name", b.getComment());
        commentCount.put("date", "评论数目");
        list.add(commentCount);

        List<Dics> dics = dicsMapper.selectByGroup("Runtime");  //肯定有数据，就不校验了
        Map<String, Object> runtime = new HashMap<>();
        runtime.put("name", dics.get(0).getValue()+"天");
        runtime.put("date", "运行天数");
        list.add(runtime);
        Subject subject = SecurityUtils.getSubject();
        Map<String, Object> userCount = new HashMap<>();
        if (subject.isAuthenticated()) {
            //当前用户就是admin,
            userCount.put("name", "当前在线");
            userCount.put("date", "运行天数");
            list.add(userCount);
        }else {
            User user = userMapper.selectById(1);
            String dateLastLogin = DateUtils.countDays(user.getLastLogin());
            userCount.put("name", dateLastLogin);
            userCount.put("date", "最后活动");
            list.add(userCount);
        }
        return list;
    }

    /**
     * 点赞
     * @param id
     * @return
     */
    @Override
    public boolean thumbUp(int id) {
        List<Blog> blogList = blogMapper.selectList(new QueryWrapper<Blog>().eq("content_id", id + ""));
        if (blogList != null && blogList.size() == 1) {
            Blog blog = blogList.get(0);
            blog.setThumbUp(blog.getThumbUp() + 1);
            blogMapper.updateById(blog);
            return  true;
        }
        return false;
    }


    @Override
    public Map<String, Content> previousAndNext(int id) {
        Map<String, Content> map = new HashMap<>();

        Content previous= contentMapper.getPreviousOrNext(id, MsgStatus.PREVIOUS_MSG);
        if (previous == null || previous.getId() == 0) {
            previous = new Content();
            Content content = contentMapper.selectById(id);
            previous.setId(content.getId());
            previous.setTitle(content.getTitle());
        }
        map.put("previous", previous);
        Content next= contentMapper.getPreviousOrNext(id, MsgStatus.NEXT_MSG);
        if (next == null || next.getId() == 0) {
            next = new Content();
            Content content = contentMapper.selectById(id);
            next.setId(content.getId());
            next.setTitle(content.getTitle());
        }
        map.put("next", next);
        return  map;
    }
}
